import time, threading, queue
import tkinter as tk
from pynput import keyboard
from ocr import ScreenReader
from PIL import Image,ImageGrab
import vgamepad as vg
import ctypes
import win32con
import win32api
import win32gui


is_looping = False
control_flag = threading.Event()
control_flag.clear()
q = queue.Queue()
screen_reader=ScreenReader()
gamepad = vg.VX360Gamepad()
gamepad.reset()
gamepad.update()

# 获取当前聚焦窗口的标题
def get_foreground_window_title():
    hwnd = win32gui.GetForegroundWindow()
    window_title = win32gui.GetWindowText(hwnd)
    return window_title

# 获取所有打开的窗口标题
def enum_windows():
    windows = []

    def enum_callback(hwnd, lParam):
        if win32gui.IsWindowVisible(hwnd):
            windows.append(win32gui.GetWindowText(hwnd))

    win32gui.EnumWindows(enum_callback, None)
    return windows


def ocr(queue):
    while (True):
        if control_flag.isSet():
            # img = Image.open('gui_gamepad.png')
            img=ImageGrab.grab()
            artifact_info=screen_reader.read_artifact(img)
            if artifact_info != None:
                is_lock=artifact_info[4]
                is_keep,_,_=screen_reader.artifact_filter(artifact_info)
                artifact_str=f"cur locked={is_lock}, keep={is_keep}, change={is_lock == is_keep}" +str(artifact_info)
                q.put(artifact_str)
                if is_lock != is_keep:
                # if True:
                    gamepad.press_button(button=vg.XUSB_BUTTON.XUSB_GAMEPAD_LEFT_THUMB)
                    gamepad.update()
                    time.sleep(0.2)
                    gamepad.release_button(button=vg.XUSB_BUTTON.XUSB_GAMEPAD_LEFT_THUMB)
                    gamepad.update()
                    time.sleep(0.2)
                gamepad.left_joystick_float(x_value_float=1.0, y_value_float=0.0)
                gamepad.update()
                time.sleep(0.2)
                gamepad.left_joystick_float(x_value_float=0.0, y_value_float=0.0)
                gamepad.update()
                time.sleep(0.2)
            else:
                time.sleep(1)
                q.put('圣遗物识别错误')
        else:
            break
    pass


class Overlay:
    def __init__(self, queue):
        self.root = tk.Tk()
        self.queue = queue
        # Set up Ping Label
        self.ping_text = tk.StringVar()
        self.ping_label = tk.Label(
            self.root,
            textvariable=self.ping_text,
            font=('Consolas', '14'),
            fg='green3',
            bg='grey19'
        )
        self.ping_label.grid(row=0, column=1)

        # Define Window Geometry
        self.root.overrideredirect(True)
        self.root.geometry("+5+75")
        self.root.lift()
        self.root.wm_attributes("-topmost", True)

    def update_label(self) -> None:
        # wait_time, update_text = self.get_new_text_callback()
        wait_time = 500
        item = self.queue.get()
        if item is not None:
            update_text = item
            self.ping_text.set(update_text)
            self.queue.task_done()
        self.root.after(wait_time, self.update_label)

    def run(self) -> None:
        self.ping_text.set('genshin auto started')
        self.root.after(500, self.update_label)
        self.root.mainloop()


def osd(queue):
    overlay = Overlay(queue)
    overlay.run()



thread_osd = threading.Thread(target=osd, args=(q,))
thread_osd.start()


def on_activate_h():
    print('<ctrl>+<alt>+y pressed')
    q.put('screen_reader starting')
    thread_ocr = threading.Thread(target=ocr, args=(q,))
    control_flag.set()
    thread_ocr.start()



def on_activate_i():
    control_flag.clear()
    # thread_ocr.join()
    print('<ctrl>+<alt>+n pressed')
    q.put('screen_reader stopped')


with keyboard.GlobalHotKeys({
    '<ctrl>+<alt>+y': on_activate_h,
    '<ctrl>+<alt>+n': on_activate_i}) as h:
    h.join()
